package cn.xiongxf.mq.consumer;

import cn.xiongxf.domain.PayOrder;
import cn.xiongxf.dto.PayOrder2MQDTO;
import cn.xiongxf.service.IPayOrderService;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.common.message.MessageExt;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import springfox.documentation.spring.web.json.Json;

import java.nio.charset.StandardCharsets;
import java.util.Date;

/**
 * 保存支付订单的消费者
 */
// MQ消息监听器
@RocketMQMessageListener(
        consumerGroup = "tx-consumer-group-courseorder",
        topic = "topic-payorder",
        selectorExpression = "tags-payorder"
)
@Component  // 交给Spring管理
@Slf4j
public class PayOrderConsumer implements RocketMQListener<MessageExt> {
    @Autowired
    private IPayOrderService payOrderService;

    @Override
    public void onMessage(MessageExt message) {
        if (message.getBody() == null || message.getBody().length == 0) return;

        // 获取支付订单DTO
        String jsonString = new String(message.getBody(), StandardCharsets.UTF_8);
        PayOrder2MQDTO payOrder2MQDTO = JSON.parseObject(jsonString, PayOrder2MQDTO.class);

        // 根据订单号从DB中查询，判断是否重复保存
        PayOrder payOrder = payOrderService.selectOne(new EntityWrapper<PayOrder>().eq("order_no", payOrder2MQDTO.getOrderNo()));
        // 已保存，返回
        if (payOrder != null) {
            log.info("消费者已保存过此支付订单啦：{}", payOrder);
            return;
        }

        // 未保存，保存
        payOrder = new PayOrder();
        BeanUtils.copyProperties(payOrder2MQDTO, payOrder);
        payOrder.setCreateTime(new Date());
        payOrder.setPayStatus(PayOrder.STATE_WAIT_PAY);
        payOrderService.insert(payOrder);
        log.info("消费者保存支付订单：{}", payOrder);
    }
}
